<?php

namespace App\Logics;


use App\Models\News;
use App\Models\NewsCate;
use App\Models\NewsDesc;
use App\Models\SiteCate;
use App\Models\NewsComment;
use App\Models\NewsTag;
use App\Models\SiteTag;
use App\Models\User;
use App\Service\Base\Logic;
use App\Service\Translate;
use App\Service\TranslateBaidu;

class NewsLogic extends Logic
{

    // 社区：文章

    // 列表查询：置顶，邮件，标红
    public function setLists($type, $number = 10)
    {
        $orderBy = "id DESC";
        $where   = [['verify', '=', 1],];
        $bang    = [];
        $noWhere = [];
        if($type == 'top'){
            // 置顶的 必须要有标题 有封面
            $orderBy = "top_time DESC";
            $bang[]  = 'is_top';
            $where   = [['verify', '=', 1], ['is_top', '=', 1], ['en_title', '!=', ""], ['pic', '!=', ""]];
            $noWhere = [['verify', '=', 1], ['en_title', '!=', ""], ['pic', '!=', ""]];
        } elseif($type == 'header'){
            $orderBy = "header_time DESC";
            $bang[]  = 'is_header';
            $where   = [['verify', '=', 1], ['is_header', '=', 1]];
        } elseif($type == 'major'){
            $orderBy = "major_time DESC";
            $bang[]  = 'is_major';
            $where   = [['verify', '=', 1], ['is_major', '=', 1]];
        }

        // 模型
        $model  = new News();
        $args   = compact('where', 'type', 'number');
        $KCache = $model->cacheKey('lists', $args);
        $lists  = $model->cacheClass()->getCache($KCache);
        // 检查是否已经绑定
        if(!empty($lists)){
            $model->checkBangList($lists, $KCache);
        }
        // 如果没有 则查询
        if(empty($lists)){
            $lists = $model->bangField($bang)->getList($where, $number, $orderBy);
            $lists = is_object($lists) ? $lists->toArray() : $lists;
            $model->addCacheList($lists, $KCache, $lists, 'list');
        }
        // 如果没有 默认的
        if(empty($lists) && $noWhere){
            $lists = $model->getList($noWhere, $number, $orderBy);
            $lists = is_object($lists) ? $lists->toArray() : $lists;
        }

        // 整理
        $lists = $this->makeNewsListsResult($lists);

        return $lists;
    }

    // 获取某一段时间内的热门：尤其是pc
    public function timeList($from, $orderBy = "id DESC")
    {
        $opt  = $this->option();
        $page = $opt->getData('page', 1, 'intval');
        $rows = $opt->getData('rows', 15, 'intval');

        // 条件
        $where   = [];
        $where[] = ['ctime', '>=', $from];


        $model = new News();
        $start = ($page - 1) * $rows;
        $lists = $model->getList($where, $rows, $orderBy, $start);
        $lists = is_object($lists) ? $lists->toArray() : $lists;

        // 整理
        $lists = $this->makeNewsListsResult($lists);

        return $lists;
    }

    // 列表查询
    public function _onLists2()
    {
        $opt     = $this->option();
        $isCount = $opt->getData('is_count', 1, 'intval');  // pc页面不用翻页
        $page    = $opt->getData('page', 1, 'intval');
        $rows    = $opt->getData('rows', 15, 'intval');
        $uid     = $opt->getData('uid', 0, 'intval');
        $is_top  = $opt->getData('is_top', null, 'intval');
        $_header = $opt->getData('is_header', null, 'intval');
        $_major  = $opt->getData('is_major', null, 'intval');
        $title   = $opt->getData('title', null, 'trim');
        $keyword = $opt->getData('keyword', null, 'trim');
        $orderBy = "id DESC";

        // 模型 和 查询  ->isCache($this->listCache)
        $where = [['verify', '=', 1]];
        $bang  = [];
        if($uid){
            $bang[]  = 'uid';
            $where[] = ['uid', '=', $uid];
        }
        if(!is_null($is_top)){
            $bang[]  = 'is_top';
            $where[] = ['is_top', '=', $is_top];
            if($is_top == 1){
                $orderBy = "top_time DESC";
            }
        }
        if(!is_null($_header)){
            $bang[]  = 'is_header';
            $where[] = ['is_header', '=', $_header];
            if($_header == 1){
                $orderBy = "header_time DESC";
            }
        }
        if(!is_null($_major)){
            $bang[]  = 'is_major';
            $where[] = ['is_major', '=', $_major];
            if($_major == 1){
                $orderBy = "major_time DESC";
            }
        }
        if($title){
            $bang    = false;
            $where[] = $this->orWhere('en_title|cn_title|tc_title', 'like', $title);
        }
        if($keyword){
            //$where[] = $this->orWhere('en_title|cn_title|tc_title|en_description|cn_description|tc_description', 'like', $keyword);
            $where[] = $this->orWhere('cn_title|cn_description', 'like', $keyword);
            $bang    = false;
        }

        // 模型
        $model  = new News();
        $args   = compact('where', 'page', 'rows', "isCount");
        $KCache = $model->cacheKey('lists', $args);
        $result = $model->cacheClass()->getCache($KCache);
        // 检查是否已经绑定
        if(!empty($result) && !empty($result['list'])){
            $model->checkBangList($result['list'], $KCache);
        }
        if(empty($result)){
            /*$start = ($page - 1) * $rows;
            $lists = $model->bangField($bang)->getList($where, $rows, $orderBy, $start);
            $lists = is_object($lists) ? $lists->toArray() : $lists;*/
            $result = $model->bangField($bang)->listPage($where, $page, $rows, $orderBy);
            if($where != false){
                $model->addCacheList($result['list'], $KCache, $result, 'list');
            }
        }

        // 整理
        $result['list'] = $this->makeNewsListsResult($result['list']);
        $result['time'] = LARAVEL_TIME;

        return $result;
    }

    // 栏目列表
    public function _cateLists()
    {
        $opt     = $this->option();
        $isCount = $opt->getData('is_count', 1, 'intval');  // pc页面不用翻页
        $page    = $opt->getData('page', 1, 'intval');
        $rows    = $opt->getData('rows', 15, 'intval');
        $uid     = $opt->getData('uid', 0, 'intval');
        $is_top  = $opt->getData('is_top', null, 'intval');
        $_header = $opt->getData('is_header', null, 'intval');
        $_major  = $opt->getData('is_major', null, 'intval');
        $_verify = $opt->getData('verify', null, 'intval');
        $title   = $opt->getData('title', null, 'trim');
        $keyword = $opt->getData('keyword', null, 'trim');
        $cate_id = $opt->getData('cate_id', null, 'intval');

        // 模型 和 查询  ->isCache($this->listCache)
        $where = [['news.verify', '=', 1]];
        $bang  = [];
        if($cate_id){
            $bang[]  = 'cate_id';
            $where[] = ['cate.cate_id', '=', $cate_id];
        }
        if($uid){
            $bang[]  = 'uid';
            $where[] = ['news.uid', '=', $uid];
        }
        if(!is_null($is_top)){
            $bang[]  = 'is_top';
            $where[] = ['news.is_top', '=', $is_top];
            if($is_top == 1){
                $orderBy = "news.top_time DESC";
            }
        }
        if(!is_null($_header)){
            $bang[]  = 'is_header';
            $where[] = ['news.is_header', '=', $_header];
            if($_header == 1){
                $orderBy = "news.header_time DESC";
            }
        }
        if(!is_null($_major)){
            $bang[]  = 'is_major';
            $where[] = ['news.is_major', '=', $_major];
            if($_major == 1){
                $orderBy = "news.major_time DESC";
            }
        }
        if($title){
            $bang    = false;
            $where[] = $this->orWhere('news.en_title|news.cn_title|news.tc_title', 'like', $title);
        }
        if($keyword){
            $bang = false;
            //$where[] = $this->orWhere('news.en_title|news.cn_title|news.tc_title|news.en_description|news.cn_description|news.tc_description', 'like', $keyword);
            $where[] = $this->orWhere('news.cn_title|news.cn_description', 'like', $keyword);
        }


        // 模型
        $model  = new News();
        $args   = compact('where', 'page', 'rows', "isCount");
        $KCache = $model->cacheKey('catelistspage', $args);
        $result = $model->cacheClass()->getCache($KCache);
        // 检查是否已经绑定
        if(($result) && (!empty($result['list']))){
            $model->checkBangList($result['list'], $KCache);
        }

        // 执行查询
        if(empty($result)){
            // 字段
            $fields = ['news.*', 'cate.news_id', 'cate.cate_id',]; // 'cate.status'
            $query  = $model->from('news_cate as cate')->join('news', 'news.id', '=', 'cate.news_id');
            $query  = $query->where($where)->select($fields)->forPage($page, $rows)->orderBy('ctime', 'DESC');
            if($isCount){
                $count = $query->where($where)->count();
            }


            // 查找过滤
            $lists  = $query->get()->toArray();
            $result = ['total' => $count, 'page' => $page, 'rows' => $rows, 'list' => $lists,];

            // 保存为缓存
            if($bang){
                $model->bangField($bang)->addCacheList($lists, $KCache, $result, 'list');
            }
        }

        // 整理
        $result['list'] = $this->makeNewsListsResult($result['list']);
        $result['time'] = LARAVEL_TIME;

        return $result;
    }

    // 标签列表
    public function _tagLists()
    {
        $opt     = $this->option();
        $isCount = $opt->getData('is_count', 1, 'intval');  // pc页面不用翻页
        $page    = $opt->getData('page', 1, 'intval');
        $rows    = $opt->getData('rows', 15, 'intval');
        $uid     = $opt->getData('uid', 0, 'intval');
        $is_top  = $opt->getData('is_top', null, 'intval');
        $_header = $opt->getData('is_header', null, 'intval');
        $_major  = $opt->getData('is_major', null, 'intval');
        $_verify = $opt->getData('verify', null, 'intval');
        $title   = $opt->getData('title', null, 'trim');
        $keyword = $opt->getData('keyword', null, 'trim');
        $tag_id  = $opt->getData('tag_id', null, 'intval');

        // 模型 和 查询  ->isCache($this->listCache)
        $where = [['news.verify', '=', 1]];
        $bang  = [];
        if($tag_id){
            $bang[]  = 'tag_id';
            $where[] = ['tag.tag_id', '=', $tag_id];
        }
        if($uid){
            $bang[]  = 'uid';
            $where[] = ['news.uid', '=', $uid];
        }
        if(!is_null($is_top)){
            $bang[]  = 'is_top';
            $where[] = ['news.is_top', '=', $is_top];
            if($is_top == 1){
                $orderBy = "news.top_time DESC";
            }
        }
        if(!is_null($_header)){
            $bang[]  = 'is_header';
            $where[] = ['news.is_header', '=', $_header];
            if($_header == 1){
                $orderBy = "news.header_time DESC";
            }
        }
        if(!is_null($_major)){
            $bang[]  = 'is_major';
            $where[] = ['news.is_major', '=', $_major];
            if($_major == 1){
                $orderBy = "news.major_time DESC";
            }
        }
        if($title){
            $bang    = false;
            $where[] = $this->orWhere('news.en_title|news.cn_title|news.tc_title', 'like', $title);
        }
        if($keyword){
            //$where[] = $this->orWhere('news.en_title|news.cn_title|news.tc_title|news.en_description|news.cn_description|news.tc_description', 'like', $keyword);
            $where[] = $this->orWhere('news.cn_title|news.cn_description', 'like', $keyword);
            $bang    = false;
        }


        // 模型
        $model  = new News();
        $args   = compact('where', 'page', 'rows', "isCount");
        $KCache = $model->cacheKey('taglistspage', $args);
        $result = $model->cacheClass()->getCache($KCache);
        // 检查是否已经绑定
        if(($result) && (!empty($result['list']))){
            $model->checkBangList($result['list'], $KCache);
        }

        // 执行查询
        if(empty($result)){
            // 字段
            $fields = ['news.*', 'tag.news_id', 'tag.tag_id',]; // 'cate.status'
            $query  = $model->from('news_tag as tag')->join('news', 'news.id', '=', 'tag.news_id');
            $query  = $query->where($where)->select($fields)->forPage($page, $rows)->orderBy('id', 'DESC');
            if($isCount){
                $count = $query->where($where)->count();
            }

            // 查找过滤
            $lists  = $query->get()->toArray();
            $result = ['total' => $count, 'page' => $page, 'rows' => $rows, 'list' => $lists,];

            // 保存为缓存
            if($bang){
                $model->bangField($bang)->addCacheList($lists, $KCache, $result, 'list');
            }
        }

        // 整理
        $result['list'] = $this->makeNewsListsResult($result['list']);
        $result['time'] = LARAVEL_TIME;

        return $result;
    }

    // 列表查询
    public function onLists()
    {
        $opt     = $this->option();
        $outTop  = $opt->getData('is_out_top', 0, 'intval');
        $isCount = $opt->getData('is_count', 1, 'intval');    // pc页面不用翻页
        $page    = $opt->getData('page', 1, 'intval');        // 获取热门等不需要翻页
        $rows    = $opt->getData('rows', 15, 'intval');
        $uid     = $opt->getData('uid', 0, 'intval');
        $is_top  = $opt->getData('is_top', null, 'intval');
        $_header = $opt->getData('is_header', null, 'intval');
        $_major  = $opt->getData('is_major', null, 'intval');
        $_email  = $opt->getData('is_email', null, 'intval');
        $s_time  = $opt->getData('start_time', 0, 'intval');
        $title   = $opt->getData('title', null, 'trim');
        $keyword = $opt->getData('keyword', null, 'trim');

        $min_id  = $opt->getData('min_id', null, 'intval');
        $max_id  = $opt->getData('max_id', null, 'intval');
        $m_time  = $opt->getData('max_time', null, 'intval');
        $tag_id  = $opt->getData('tag_id', null, 'intval');
        $cate_id = $opt->getData('cate_id', null, 'intval');
        $_verify = $opt->getData('verify', null, 'intval');

        // 排序
        $is_hot  = $opt->getData('is_hot', null, 'intval');
        $is_new  = $opt->getData('is_new', null, 'intval');
        $orderBy = "apt_news.id DESC";
        $orderBy = "apt_news.ctime DESC";
        if($is_hot){
            $orderBy = "apt_news.virtual_no DESC";
        }
        if($is_new){
            $orderBy = "apt_news.ctime DESC";
        }

        // 模型 和 查询  ->isCache($this->listCache)
        $where = [['news.verify', '=', 1], ['news.is_draft', '=', 0]];
        $bang  = ['verify', 'is_draft'];
        if($cate_id){
            $bang[]  = 'cate_id';
            $where[] = ['cate.cate_id', '=', $cate_id];
            $where[] = ['cate.status', '=', 1];
        }
        if($m_time){
            $where[] = ['news.ctime', '>', $m_time];
        }
        if($tag_id){
            $bang[]  = 'tag_id';
            $where[] = ['tag.tag_id', '=', $tag_id];
        }
        if($uid){
            $bang[]  = 'uid';
            $where[] = ['news.uid', '=', $uid];
        }
        if(!is_null($_email)){
            $bang[]  = 'is_email';
            $where[] = ['news.is_email', '=', $_email];
            if($is_top == 1){
                $orderBy = "apt_news.email_time DESC";
            }
        }
        if(!is_null($is_top)){
            // 置顶的 必须要有标题 有封面
            $bang[]  = 'is_top';
            $where[] = ['news.is_top', '=', $is_top];
            $where[] = ['news.en_title', '!=', ""];
            $where[] = ['news.pic', '!=', ""];
            if($is_top == 1){
                $orderBy = "apt_news.top_time DESC";
            }
        }
        if(!is_null($_header)){
            $bang[]  = 'is_header';
            $where[] = ['news.is_header', '=', $_header];
            if($_header == 1){
                $orderBy = "apt_news.header_time DESC";
            }
        }
        if(!is_null($_major)){
            $bang[]  = 'is_major';
            $where[] = ['news.is_major', '=', $_major];
            if($_major == 1){
                $orderBy = "apt_news.major_time DESC";
            }
        }
        if($max_id){
            $bang    = false;
            $where[] = ['news.id', '>', $max_id];
        }
        if($min_id){
            $bang    = false;
            $where[] = ['news.id', '<', $min_id];

        }
        if($s_time){
            $bang    = false;
            $where[] = ['news.ctime', '>=', $s_time];
        }
        if($title){
            $bang    = false;
            $where[] = $this->orWhere('news.en_title|news.cn_title|news.tc_title', 'like', $title);
        }
        if($keyword){
            //$where[] = $this->orWhere('news.en_title|news.cn_title|news.tc_title|news.en_description|news.cn_description|news.tc_description', 'like', $keyword);

            // 先翻译
            $translate_type = 'google';    // google  baidu
            if($translate_type == 'google'){
                $translate = new Translate();   // 谷歌翻译
                $result1   = $translate->translateTo($keyword, 'en');
                $keyword   = $result1['text'];
            } else{
                $translate = new TranslateBaidu();  // 百度翻译：不能翻译html
                $result1   = $translate->run($keyword, 'zh', 'en');
                $res1      = json_decode($result1, true);
                if(empty($res1['error_msg'])){
                    $data    = $res1['result'];
                    $keyword = $data['trans_result'][0]['dst'];
                    //var_dump($data);
                    //echo '源语种：'.$data['from'].'<br>';
                    //echo '目标语种：'.$data['to'].'<br>';
                    //echo '源文本：'.$data['trans_result'][0]['src'].'<br>';
                    //echo '目标文本：'.$data['trans_result'][0]['dst'].'<br>';
                } else{
                    return $this->_returnFail($res1['error_msg']);
                }
            }

            $where[] = $this->orWhere('news.en_title|news.en_description', 'like', $keyword);
            $bang    = false;
        }

        // 获取所有的文章的时候 第一页不展示突发的top新闻
        $model  = new News();
        $outIds = [];
        //$this->log($where,'条件');
        //$this->log(count($where),'条件个数');
        if($outTop && (count($where) == 1) && ($page == 1)){
            $topWhere   = [['verify', '=', 1], ['is_top', '=', 1], ['en_title', '!=', ""], ['pic', '!=', ""]];
            $topOrderBy = "top_time DESC";
            $topBang[]  = 'is_top';
            $topNumber  = $outTop > 1 ? $outTop : 3;
            // 模型
            $args    = compact('topWhere', 'topNumber');
            $KCache  = $model->cacheKey('lists', $args);
            $topList = $model->cacheClass()->getCache($KCache);
            // 检查是否已经绑定
            if(!empty($topList)){
                $model->checkBangList($topList, $KCache);
            }
            if(empty($topList)){
                $topList = $model->bangField($topBang)->getList($topWhere, $topNumber, $topOrderBy);
                $topList = is_object($topList) ? $topList->toArray() : $topList;
                $model->addCacheList($topList, $KCache, $topList, 'list');
            }

            // 如果没有查询 到 则重新查询
            $noWhere = [['verify', '=', 1], ['en_title', '!=', ""], ['pic', '!=', ""]];
            // 如果没有 默认的
            if(empty($lists)){
                $lists   = $model->getList($noWhere, $topNumber, $orderBy);
                $topList = is_object($lists) ? $lists->toArray() : $lists;
            }

            // 排除显示的ID
            $outIds = array_column($topList, 'id');
            $this->log($outIds, 'ids');
        }

        // 模型
        $args   = compact('where', 'page', 'rows', "isCount", "bang", "_verify", "orderBy", 'outIds');
        $KCache = $model->cacheKey('taglistspage', $args);
        $result = $model->cacheClass()->getCache($KCache);
        // 检查是否已经绑定
        if(($result) && (!empty($result['list']))){
            $model->checkBangList($result['list'], $KCache);
        }

        /*var_dump($opt->getData());
        echo '<br><br><br>';
        var_dump($where);
        echo '<br><br><br>';*/

        // 执行查询
        if(empty($result)){
            // 字段
            $fields = ['news.*',];
            $query  = $model->from('news');   // 查询
            if($cate_id){
                $fields[] = 'cate.news_id';
                $fields[] = 'cate.cate_id';
                // 查询
                $query = $query->join('news_cate as cate', 'news.id', '=', 'cate.news_id');
            }
            if($tag_id){
                $fields[] = 'tag.news_id';
                $fields[] = 'tag.tag_id';
                // 查询
                $query = $query->join('news_tag as tag', 'news.id', '=', 'tag.news_id');
            }
            if($outIds){
                $query = $query->whereNotIn('id', $outIds);   // 查询
            }

            // 查询统计  统计必须在查询之前之前，不然只统计查询到的数据
            $query = $query->where($where)->select($fields)->orderByRaw($orderBy);
            if($isCount){
                $count = $query->count();
            }

            // 查找列表
            if($page && empty($min_id) && empty($max_id)){
                $lists = $query->forPage($page, $rows)->get()->toArray();
            } else{
                $lists = $query->limit($rows)->get()->toArray();
            }

            // 组合
            $result = ['rows' => $rows, 'list' => $lists,];
            if($isCount){
                $result['total'] = $count;
            }
            if($page){
                $result['page'] = $page;
            }

            // 保存为缓存
            if($bang){
                $model->bangField($bang)->addCacheList($lists, $KCache, $result, $result);
            }
        }

        // 整理
        $result['list'] = $this->makeNewsListsResult($result['list']);
        $result['time'] = LARAVEL_TIME;
        $result['date'] = date("Y-m-d", LARAVEL_TIME);

        return $result;
    }

    // 详情
    public function onShow($myUid = 0, $options = [])
    {
        $opt = $this->option();
        //$opt->setField('is_first', 1);  // 返回详情第一段

        $_id  = $opt->getData('id', null, 'intval');
        $link = $opt->getData('link', null, 'trim');
        $page = $opt->getData('page', 1, 'intval');
        $rows = $opt->getData('rows', 15, 'intval');
        if(empty($_id) && empty($link)){
            return $this->_returnFail('select_operation_id');
        }

        // 条件
        if($_id){
            $where = ['id' => $_id];
        } else{
            $where = ['link' => $link];
        }

        // 组合数据
        $model = new News();
        $info  = $model->isCache(true)->oneFind($where);
        if($info === false){
            return $this->_returnFail($model->getError());
        }
        if($info['verify'] == -1){
            return $this->_returnFail("news_has_no_exist");
        }

        // 整理
        $info = $this->makeNewsInfoResult($info, $options);

        // 阅读量
        $model->addView($_id);

        // 获取评论
        $where2 = [['news_id', '=', $_id]];  // ['verify', '=', 1],
        $model  = new NewsComment();
        $args   = compact('where2', 'page', 'rows');
        $KCache = $model->cacheKey('lists', $args);
        $lists  = $model->cacheClass()->getCache($KCache);
        // 检查是否已经绑定
        if(!empty($lists)){
            $model->checkBangList($lists, $KCache);
        }

        // 查询评论数据
        if(empty($lists)){
            //$result = $model->bangField($bang)->listPage($where, $page, $rows, "id DESC");
            $start = ($page - 1) * $rows;
            $lists = $model->bangField(['news_id'])->getList($where2, $rows, "id DESC", $start);
            $lists = is_object($lists) ? $lists->toArray() : $lists;
            if($where2 != false){
                $model->addCacheList($lists, $KCache, $lists, 'list');
            }
        }

        // 处理评论
        if(!empty($lists)){
            $uids  = array_column($lists, 'uid');
            $users = (new User())->isCache(true)->getListInIds($uids);
            foreach($lists as &$item){
                $_uid = $item['uid'];
                // 匹配用户
                $item['user'] = $users[$_uid] ?? [];
            }
        }

        // 组合
        $info['show_link'] = atwUrl('article', $info);
        $info['comment']   = $lists;


        return $info;
    }

    // 软删除
    public function toSoft($myUid)
    {
        $_id = $this->id();
        if(empty($_id)){
            return $this->_returnFail('select_operation_id');
        }

        $where  = ['id' => $_id, 'uid' => $myUid];
        $model  = new News();
        $result = $model->isCache(true)->oneEdit($where, ['verify' => -1]);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }

    // 改变（直接修改，软删除，改变状态，排序）
    public function onEdit($myUid)
    {
        $_id = $this->id();
        if(empty($_id)){
            return $this->_returnFail('select_operation_id');
        }

        // 组合参数
        $opt   = $this->option();
        $cates = $opt->getData("cates", [], "is_array");
        $tags  = $opt->getData("tags", [], "is_array");
        if(empty($cates)){
            return $this->_returnFail('select_the_posting_cate');
        }

        $data = [
            //'id' => $opt->getData("id", null, "intval"),
            'uid'            => $myUid,
            'pic'            => $opt->getData("pic", null, "trim"),
            'ip'             => $opt->getIp(),

            // 各个语言的字段
            'en_title'       => $opt->getData("en_title", null, "trim"),
            'cn_title'       => $opt->getData("cn_title", null, "trim"),
            'tc_title'       => $opt->getData("tc_title", null, "trim"),
            'en_keywords'    => $opt->getData("en_keywords", null, "trim"),
            'cn_keywords'    => $opt->getData("cn_keywords", null, "trim"),
            'tc_keywords'    => $opt->getData("tc_keywords", null, "trim"),
            'en_description' => $opt->getData("en_description", null, "trim"),
            'cn_description' => $opt->getData("cn_description", null, "trim"),
            'tc_description' => $opt->getData("tc_description", null, "trim"),
            'en_content'     => $opt->getData("en_content", null, "trim"),
            'cn_content'     => $opt->getData("cn_content", null, "trim"),
            'tc_content'     => $opt->getData("tc_content", null, "trim"),

            // 其他
            'images'         => $opt->getData("images", '[]', "json_decode"),
            'author'         => $opt->getData("author", null, "trim"),
            'verify'         => $opt->getData("verify", 1, "intval"),
            'is_top'         => $opt->getData("is_top", null, "intval"),
            'is_header'      => $opt->getData("is_header", null, "intval"),
            'is_major'       => $opt->getData("is_major", null, "intval"),
            'push_time'      => $opt->getData("push_time", null, "intval"),
            'is_draft'       => $opt->getData("is_draft", 0, "intval"),
            //'read_no'     => $opt->getData("read_no", null, "intval"),
            //'virtual_no'  => $opt->getData("virtual_no", null, "intval"),
            //'praise_no'   => $opt->getData("praise_no", null, "intval"),
            //'collect_no'  => $opt->getData("collect_no", null, "intval"),
            //'relay_no'    => $opt->getData("relay_no", null, "intval"),
            //'comment_no'  => $opt->getData("comment_no", null, "intval"),
            //'ip_address'  => $opt->getData("ip_address", null, "trim"),
            //'ctime'       => $opt->getData("ctime", null, "intval"),
            //'mtime'       => $opt->getData("mtime", null, "intval"),
        ];


        $data = $this->filterNull($data);
        if(empty($data)){
            return $this->_returnFail('add_the_saved_data');
        }
        if($data === false){
            return $this->_returnFail('add_the_saved_data');
        }
        // 组合数据
        /*$where = ['id' => $_id, 'uid' => $myUid];
        $data  = $model->checkData($data, $where);
        if($data === false){
            return $this->_returnFail('add_the_saved_data');
        }*/

        // 验证
        $model  = new News();
        $result = $model->checkRules($data, 'edit');
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        // 保存
        $result = $model->publish($myUid, $data, $cates, $tags);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }

    // 树状
    public function onAdd($myUid)
    {
        // 组合参数
        $opt   = $this->option();
        $cates = $opt->getData("cates", [], "is_array");
        $tags  = $opt->getData("tags", [], "is_array");
        if(empty($cates)){
            return $this->_returnFail('select_the_posting_cate');
        }

        $data = [
            //'id' => $opt->getData("id", null, "intval"),
            'uid'            => $myUid,
            'pic'            => $opt->getData("pic", null, "trim"),
            'ip'             => $opt->getIp(),

            // 各个语言的字段
            'en_title'       => $opt->getData("en_title", null, "trim"),
            'cn_title'       => $opt->getData("cn_title", null, "trim"),
            'tc_title'       => $opt->getData("tc_title", null, "trim"),
            'en_keywords'    => $opt->getData("en_keywords", null, "trim"),
            'cn_keywords'    => $opt->getData("cn_keywords", null, "trim"),
            'tc_keywords'    => $opt->getData("tc_keywords", null, "trim"),
            'en_description' => $opt->getData("en_description", null, "trim"),
            'cn_description' => $opt->getData("cn_description", null, "trim"),
            'tc_description' => $opt->getData("tc_description", null, "trim"),
            'en_content'     => $opt->getData("en_content", null, "trim"),
            'cn_content'     => $opt->getData("cn_content", null, "trim"),
            'tc_content'     => $opt->getData("tc_content", null, "trim"),

            // 其他
            'images'         => $opt->getData("images", '[]', "json_decode"),
            'author'         => $opt->getData("author", null, "trim"),
            'verify'         => $opt->getData("verify", 1, "intval"),
            'is_top'         => $opt->getData("is_top", null, "intval"),
            'is_header'      => $opt->getData("is_header", null, "intval"),
            'is_major'       => $opt->getData("is_major", null, "intval"),
            'push_time'      => $opt->getData("push_time", null, "intval"),
            'is_draft'       => $opt->getData("is_draft", 0, "intval"),
            //'read_no'     => $opt->getData("read_no", null, "intval"),
            //'virtual_no'  => $opt->getData("virtual_no", null, "intval"),
            //'praise_no'   => $opt->getData("praise_no", null, "intval"),
            //'collect_no'  => $opt->getData("collect_no", null, "intval"),
            //'relay_no'    => $opt->getData("relay_no", null, "intval"),
            //'comment_no'  => $opt->getData("comment_no", null, "intval"),
            //'ip_address'  => $opt->getData("ip_address", null, "trim"),
            //'ctime'       => $opt->getData("ctime", null, "intval"),
            //'mtime'       => $opt->getData("mtime", null, "intval"),
        ];
        $data = $this->filterNull($data);
        if(empty($data)){
            return $this->_returnFail('add_the_saved_data');
        }

        // 组合数据
        $model = new News();
        $data  = $model->checkData($data);
        if($data === false){
            return $this->_returnFail('add_the_saved_data');
        }

        // 验证
        $result = $model->checkRules($data, 'add');
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        // 保存
        //$result = $model->oneAdd($data);
        $result = $model->publish($myUid, $data, $cates, $tags);
        if($result === false){
            return $this->_returnFail($model->getError());
        }

        return $result;
    }

    // 整理结果
    protected function makeNewsListsResult($list)
    {
        if(empty($list)){
            return $list;
        }

        $opt        = $this->option();
        $is_replace = $opt->getData('is_replace', 0, 'intval');  // 是否将描述替换成内容
        $is_cate    = $opt->getData('is_cate', 0, 'intval');  // 返回栏目
        $is_tag     = $opt->getData('is_tag', 0, 'intval');  // 返回标签
        $is_first   = $opt->getData('is_first', 0, 'intval');  // 返回第一段


        // 设置语言
        $is_en     = 1;
        $is_cn     = 1;
        $is_tc     = 1;
        $_language = $opt->getData('language', [], 'is_array');  // 设置语言
        if($_language){
            $is_en = in_array('en', $_language);
            $is_cn = in_array('cn', $_language);
            $is_tc = in_array('tc', $_language);
        }


        // 返回编辑作者
        $sCateDb = new SiteCate();
        $sTagDb  = new SiteTag();
        $nCateDb = new NewsCate();
        $nTagDb  = new NewsTag();
        //$userDb  = new User();
        //$uids    = array_unique(array_column($list, 'uid'));
        //$users   = $userDb->isCache(true)->getListInIds($uids);  // ->isCache(true)  // 缓存要报错

        // 是否将内容替换成内容
        //  在app上，描述不足，需要内容来替换
        if($is_replace || $is_first){
            $newsIds = array_column($list, 'id');
            $descDb  = new NewsDesc();
            $descs   = $descDb->isCache(true)->getListInIds($newsIds, '*', 'news_id');
            if($is_first){
                foreach($descs as $_key => $_desc){
                    $number = 0;
                    $strpos = strpos($_desc['en_content'], '<img');
                    if($strpos !== false){
                        $number = $strpos > 50 ? 0 : 1;  // 可能有p标签
                    }

                    // 截取第一段
                    $en_contents = explode('</p>', $_desc['en_content']);
                    $cn_contents = explode('</p>', $_desc['cn_content']);
                    $tc_contents = explode('</p>', $_desc['tc_content']);

                    // 重新组合
                    $descs[$_key]['en_content'] = ($en_contents[$number] ?? $en_contents[0]).'</p>';
                    $descs[$_key]['cn_content'] = ($cn_contents[$number] ?? $cn_contents[0]).'</p>';
                    $descs[$_key]['tc_content'] = ($tc_contents[$number] ?? $tc_contents[0]).'</p>';
                }
            }
        }


        // 整理
        $domain    = env('STYLE_HOST');
        $oldDomain = env('OLD_HOST');
        foreach($list as &$item){
            $_uid    = $item['uid'];
            $_newsId = $item['id'];

            // 整理标签信息
            if($is_tag){
                $tags  = [];
                $nTags = $nTagDb->isCache(true)->getList(['news_id' => $_newsId]);
                if($nTags){
                    $tagIds = array_column($nTags, 'tag_id');
                    $tags   = $sTagDb->isCache(true)->getListInIds($tagIds);
                    $tags   = array_values($tags);
                }
                // 整理
                $item['tags'] = $tags;
            }

            // 整理栏目信息信息
            if($is_cate){
                $cates   = [];
                $en_cate = '';
                $nCates  = $nCateDb->isCache(true)->getList(['news_id' => $_newsId]);
                if($nCates){
                    $cateIds = array_column($nCates, 'cate_id');
                    $cates   = $sCateDb->isCache(true)->getListInIds($cateIds);
                    $cates   = array_values($cates);
                    foreach($cates as $_cate){
                        $en_cate = $_cate['en_title'];
                    }
                }
                // 整理
                $item['cates']   = $cates;
                $item['en_cate'] = $en_cate;
            }


            // 改变图片域名地址
            if($item['pic']){

                /*// 分割 URL
                $urlParts = parse_url($item['pic']);
                $protocol = $urlParts['scheme'].'://';
                $path     = $urlParts['path'];
                // 对路径部分进行编码
                $encodedPath = urlencode($path);
                // 组合新的 URL
                $item['pic'] = $protocol.$encodedPath;*/

                $item['pic'] = str_replace($oldDomain, $domain, $item['pic']);
                //$item['pic'] = $this->getChinaUrl($item['pic']);
            }
            // 图片集
            //$userInfo       = isset($users[$_uid]) ? $users[$_uid] : (object)[];
            $item['images'] = json_decode($item['images']);
            if($item['images']){
                $images = [];
                foreach($item['images'] as $_img){
                    $images[] = str_replace($oldDomain, $domain, $_img);
                }
                // 整理
                $item['images'] = $images;
            }


            // 组合
            if(!empty($descs[$_newsId]['en_content'])){
                $item['en_description'] = strip_tags($descs[$_newsId]['en_content']);
            }
            if(!empty($descs[$_newsId]['cn_content'])){
                $item['cn_description'] = strip_tags($descs[$_newsId]['cn_content']);
            }
            if(!empty($descs[$_newsId]['tc_content'])){
                $item['tc_description'] = strip_tags($descs[$_newsId]['tc_content']);
            }
            if($item['en_description']){
                $item['en_description'] = str_replace("\n", "", $item['en_description']);
            }
            if($item['cn_description']){
                $item['cn_description'] = str_replace("\n", "", $item['cn_description']);
            }
            if($item['tc_description']){
                $item['tc_description'] = str_replace("\n", "", $item['tc_description']);
            }

            // 语言设置
            if(empty($is_en)){
                unset($item['en_description']);
            }
            if(empty($is_cn)){
                unset($item['cn_description']);
            }
            if(empty($is_tc)){
                unset($item['tc_description']);
            }

            // 整理
            //$item['user']    = isset($users[$_uid]) ? $users[$_uid] : [];
            //$item['user']    = $userInfo;
            // 头像
            /*if($item['user']){
                $item['user']['head_img'] = $this->getFullUrl($item['user']['head_img']);
            }*/
        }

        return $list;
    }

    // 图片地址中含有中文 在app上不能显示 需进行编码
    public function getChinaUrl($url)
    {
        $newUrl   = '';
        $urlParts = explode('/', $url);  // 分割 URL
        $noEncode = ['http:', 'https:'];

        //  var_dump(urlencode($url));
        //  var_dump(rawurlencode($url));
        // 组合
        $count = count($urlParts);
        $comm  = '/';
        foreach($urlParts as $key => $value){
            // 最后的时候不能是 /
            if($count <= $key + 1){
                $comm = '';
            }

            // 执行拼接
            if(in_array($value, $noEncode)){
                $newUrl .= $value.$comm;
            } else{
                $newUrl .= rawurlencode($value).$comm;
            }
        }

        return $newUrl;
    }

    // 图片地址中含有中文 在app上不能显示 需进行编码
    public function getChinaUrl3($url)
    {
        // 分割 URL
        $urlParts = parse_url($url);
        if(empty($urlParts['scheme'])){
            return '';
        }


        // 组合新的 URL
        $protocol  = $urlParts['scheme'].'://'.$urlParts['host'];
        $encodPath = urlencode($urlParts['path']);  // 对路径部分进行编码
        $newUrl    = $protocol.$encodPath;

        return $newUrl;
    }

    // 整理结果
    protected function makeNewsInfoResult($info, $options = [])
    {
        if(empty($info)){
            return $info;
        }

        // 配置参数
        $is_first  = $options['is_first'] ?? 0;  // 返回第一段
        $is_remove = $options['remove_content_pic'] ?? 0;  // 删除内容中的图片
        $first_pic = $options['first_content_is_pic'] ?? 0;  // 判断 content 第一段是否有图片

        // 改变图片域名地址
        $domain    = env('STYLE_HOST');
        $oldDomain = env('OLD_HOST');
        if($info['pic']){
            $info['pic'] = str_replace($oldDomain, $domain, $info['pic']);
        }
        if($info['tc_content']){
            $info['tc_content'] = str_replace($oldDomain, $domain, $info['tc_content']);
            if($is_remove){
                $info['tc_content'] = strip_tags($info['tc_content'], '<p><a><br><div>');  // 删除内容中的图片
            } else{
                $info['tc_content'] = strip_tags($info['tc_content'], '<p><a><img><br><div>');
            }
        }
        if($info['en_content']){
            $info['en_content'] = str_replace($oldDomain, $domain, $info['en_content']);
            if($is_remove){
                $info['en_content'] = strip_tags($info['en_content'], '<p><a><br><div>');  // 删除内容中的图片
            } else{
                $info['en_content'] = strip_tags($info['en_content'], '<p><a><img><br><div>');
            }
        }
        if($info['cn_content']){
            $info['cn_content'] = str_replace($oldDomain, $domain, $info['cn_content']);
            if($is_remove){
                $info['cn_content'] = strip_tags($info['cn_content'], '<p><a><br><div>');  // 删除内容中的图片
            } else{
                $info['cn_content'] = strip_tags($info['cn_content'], '<p><a><img><br><div>');
            }
        }


        // 图片集
        $info['images'] = json_decode($info['images']);
        if($info['images']){
            $images = [];
            foreach($info['images'] as $_img){
                $images[] = str_replace($oldDomain, $domain, $_img);
            }
            // 整理
            $info['images'] = $images;
        }

        // 整理
        $info['first_pic'] = 0;  // 第一段是否有图片
        if($is_first){
            $number = 0;
            $strpos = strpos($info['en_content'], '<img');
            if($strpos !== false){
                //$number = $strpos > 50 ? 0 : 1;  // 可能有p标签
                if($strpos > 50){
                    $number = 1;
                } else{
                    $info['first_pic'] = 1;  // 第一段是否有图片
                }
            }

            // 截取第一段
            $en_contents = explode('</p>', $info['en_content']);
            $cn_contents = explode('</p>', $info['cn_content']);
            $tc_contents = explode('</p>', $info['tc_content']);

            // 重新组合
            $info['en_description'] = strip_tags(($en_contents[$number] ?? $en_contents[0]).'</p>');
            $info['cn_description'] = strip_tags(($cn_contents[$number] ?? $cn_contents[0]).'</p>');
            $info['tc_description'] = strip_tags(($tc_contents[$number] ?? $tc_contents[0]).'</p>');
        }

        $info['en_description'] = str_replace("\n", "", $info['en_description']);
        $info['cn_description'] = str_replace("\n", "", $info['cn_description']);
        $info['tc_description'] = str_replace("\n", "", $info['tc_description']);

        // 头像
        /*if($info['user']){
            $info['user']['head_img'] = $this->getFullUrl($info['user']['head_img']);
        }*/

        return $info;
    }
}


